package server

import (
	"animal/octopus/common"
	"animal/octopus/config"
	"animal/octopus/model"

	log "github.com/sirupsen/logrus"
)

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func migrateSqliteModel(model interface{}) error {
	err := common.DB(nil).AutoMigrate(model)
	if err != nil {
		log.Errorf("migrate %T failed: %s", model, err)
		return err
	}
	log.Infof("migrate %T success", model)
	return nil
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func migrateMysqlModel(model interface{}) error {
	err := common.DB(nil).Set("gorm:table_options", "CHARSET=utf8").AutoMigrate(model)
	if err != nil {
		log.Errorf("migrate %T failed: %s", model, err)
		return err
	}
	log.Infof("migrate %T success", model)
	return nil
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func initMysqlTables(models []interface{}) error {
	for _, model := range models {
		if err := migrateMysqlModel(model); err != nil {
			return err
		}
	}
	return nil
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func initSqliteTables(models []interface{}) error {
	for _, model := range models {
		if err := migrateSqliteModel(model); err != nil {
			return err
		}
	}
	return nil
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func initTables() error {
	models := []interface{}{
		&model.Module{},
		&model.Dependency{},
		&model.TopoView{},
		&model.TopoRule{},
		&model.ReportRule{},
		&model.Event{},
	}

	if config.Instance().Data.Mysql.Name != "" {
		return initMysqlTables(models)
	} else {
		return initSqliteTables(models)
	}
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func InitDB(drop bool) error {
	err := common.OpenDatabase(drop)
	if err != nil {
		log.Fatal("open database failed")
		return err
	}

	return initTables()
}
